<?php
namespace app\api\controller;
use app\api\controller\Weixin;
use app\common\model\Img as ImgModel;
use app\common\model\Audio as AudioModel;
use app\common\model\Video as VideoModel;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\BucketManager;
use think\Controller;
use think\Db;

/**
 * 上传接口
 * Class Getchildarea
 * @package app\api\controller
 */
class Upload extends Controller
{
    protected $img_model;
    protected $audio_model;
    protected $video_model;

    //ico图片上传
    public function ico() {
        $config = [
            'size' => 20971520,
            'ext'  => 'ico'
        ];

        $file = $this->request->file('file');

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $url=str_replace('\\', '/', $info->getSaveName());
            $result = [
                'error' => 0,
                'url'   => $url
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }
        return json($result);
    }

    //图片上传
    public function img() {
        $this->img_model       = new ImgModel();

        $config = [
            'size' => 20971520,
            'ext'  => 'jpg,gif,png,bmp,ico'
        ];

        $file = $this->request->file('file');

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $url=str_replace('\\', '/', $info->getSaveName());
            $image = \think\Image::open(ROOT_PATH .'public/uploads/'.$url);
            // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
            $image->thumb(800,800,1)->save(ROOT_PATH .'public/uploads/'.$url);
            $img_data['url']= $url;
            $this->img_model->save($img_data);

            $result = [
                'error' => 0,
                'imgid'   =>$this->img_model->id,
                'url'   => $url
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }

    //图片上传
    public function wximg() {
        $this->img_model       = new ImgModel();
        $Weixin=new Weixin();
        $temporary_material=$Weixin->temporary_material($this->request->post('media_id'));
        $suijishu=date('YmdHis').strrev(substr(uniqid(),7,13));
        $date=date("Ymd");
        $path = "./public/uploads/".$date."/"; //上传路径
        if (!is_dir($path)) mkdir($path);
        $filename = $path.$suijishu.".jpg";
        $this->saveWeixinFile($filename,$temporary_material);
        //图片地址
        $img=$date."/".$suijishu.".jpg";

        if(file_exists($filename)){
            $img_data['url']= $img;
            $this->img_model->save($img_data);

            $data['imgid']=$this->img_model->id;
            $data['url']=$img;

            $result = [
                'status' => "ok",
                'message' =>"上传成功",
                'data'   => $data
            ];
        } else {
            $result = [
                'status'   => "fail",
                'message' => "上传失败"
            ];
        }

        return json($result);
    }

    //音频上传
    public function audio(){
        $this->audio_model       = new AudioModel();

        $config = [
            'size' => 209715200,
            'ext'  => 'mp3,m4a,wav'
        ];

        $file = $this->request->file('file');

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $url=str_replace('\\', '/', $info->getSaveName());
            $audio_data['url']= $url;
            $this->audio_model->save($audio_data);

            $result = [
                'error' => 0,
                'audioid'   =>$this->audio_model->id,
                'url'   => $url
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }

    //音频上传
    public function wxaudio() {
        $this->audio_model       = new AudioModel();

        $Weixin=new Weixin();
        $temporary_material=$Weixin->temporary_material($this->request->post('media_id'));
        $suijishu=date('YmdHis').strrev(substr(uniqid(),7,13));
        $date=date("Ymd");
        $path = "./public/uploads/".$date."/"; //上传路径
        if (!is_dir($path)) mkdir($path);
        $filename = $path.$suijishu.".amr";
        $this->saveWeixinFile($filename,$temporary_material);
        //图片地址
        $url=$date."/".$suijishu.".mp3";

        if(file_exists($filename)){
            $file=$this->QiniuChangeFile($date."/".$suijishu);

            if($file){
                $audio_data['url']= $url;
                $this->audio_model->save($audio_data);

                $data['urlid']=$this->audio_model->id;
                $data['url']=$url;

                $result = [
                    'status' => "ok",
                    'message' =>"上传成功",
                    'data'   => $data
                ];
            } else {
                $result = [
                    'status'   => "fail",
                    'message' => "上传失败"
                ];
            }
        }else{
            $result = [
                'status'   => "fail",
                'message' => "上传失败"
            ];
        }

        return json($result);
    }

    //视频上传
    public function video() {
        $this->video_model       = new VideoModel();

        $config = [
            'size' => 2009715200,
            'ext'  => 'mp4'
        ];

        $file = $this->request->file('file');

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $url=str_replace('\\', '/', $info->getSaveName());
            $video_data['url']= $url;
            $this->video_model->save($video_data);

            $result = [
                'error' => 0,
                'videoid'   =>$this->video_model->id,
                'url'   => $url
            ];

        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }

    function saveWeixinFile($filename, $filecontent)
    {
        $local_file = fopen($filename, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file, $filecontent)) {
                fclose($local_file);
            }
        }
    }


    //七牛云文件的转换 ,amr转换成MP3处理和七牛云以及本地的文件存储处理
    // amr文件上传到七牛云->转换成MP3格式->删除七牛云上amr文件->下载MP3格式到本地->删除七牛云上的MP3文件->删除本地的amr文件
    //1.封装性还不够好 其实要做的话每一步都要封装成一个独立的函数 2.还有严谨性 比如每个删除的时候都要判断下这个文件是否存在
    public function QiniuChangeFile($card_id){
        $date = [];

        $filePath="./public/uploads/".$card_id.".amr";  //本地文件路径
        $accessKey = "A7rl4nf_i3PZnSt3xd05bTId-BVW-Ncj-Hw94cDM";      //七牛公钥
        $secretKey = "Oua5Wp2UaNpqfEnDRZ_9J-Sba4ZsDxNLrKEb3mBd";      //七牛私钥
        $auth = new Auth($accessKey, $secretKey);
        $bucket = "longfangyun";     //七牛云存储空间
        $munber=time();
        $key = $munber.'.amr';   //七牛云中保存的amr文件命名

        $pipeline='917130769';  //自己创建的私有队列 速度更快

        $notifyUrl = '';  //转码完成后通知到你的业务服务器。
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);

        $fops = "avthumb/mp3/ab/320k/ar/44100/acodec/libmp3lame|saveas/" . \Qiniu\base64_urlSafeEncode($bucket . ":".$munber.".mp3");
        $policy = array(   //使用私有队列  公有队列速度太慢
            'persistentOps' => $fops,
            'persistentPipeline' => $pipeline
        );
        $force = false;
        //指定上传命令
        $uptoken = $auth->uploadToken($bucket, $key, 3600, $policy);

        $uploadMgr = new UploadManager();

        //上传文件并转码$filePath为本地文件路径
        list($ret, $err) = $uploadMgr->putFile($uptoken, $key, $filePath);
        if ($err !== null) {
            return false;
        }else {
            $result = $pfop->execute($bucket, $key, $fops, $policy, $notifyUrl, $force);   //转码操作
            //   var_dump($result);
            //此时七牛云中同一段音频文件有amr和MP3两个格式的两个文件同时存在
            //$bucketMgr = new BucketManager($auth);
            //为节省空间,删除amr格式文件
            //$bucketMgr->delete($bucket, $key);

            //程序暂停一段时间 等待转码完成
            sleep(2);
            $i=0;
            $url = 'http://baoqing.img.lysoo.com/'.$munber.'.mp3';
            if(@fopen($url, 'r')) {
                //下载回本地   还要删除七牛云MP3格式避免占空间  同时也要删除本地的amr格式的文件
                $Qiniu_file = file_get_contents('http://baoqing.img.lysoo.com/'.$munber.'.mp3');
                $save_path = './public/uploads/'.$card_id.'.mp3';  //本地文件路径和文件名
                file_put_contents($save_path, $Qiniu_file);

                //$bucketMgr->delete($bucket, $munber.'.mp3');   //删除七牛MP3文件

                $date = [
                    'status' => "ok",
                    'message' =>"上传成功"
                ];
            } else {
                if($i<8){
                    $i=$i+1;
                    sleep(1);
                }else{
                    $date = [
                        'status'   => "fail",
                        'message' => "上传失败"
                    ];
                }
            }

        }

        return json($date);
    }
}